import json
import httpx
from typing import Any
import os
from dotenv import load_dotenv
load_dotenv()
# 汽车入厂API配置
NAVIGATION_QUERY = os.getenv("BASEA_CAR_URL", "") + "/jreap/web/right/auth/v1/navigation.form"
FUEL_TOKEN = os.getenv("FUEL_TOKEN", "")

async def jump_url(pageName: str) -> dict[str, Any] | None:
    headers = {
        "Content-Type": "application/json"
    }
    # 汽车入厂API配置
    NAVIGATION_QUERY = os.getenv("BASEA_CAR_URL", "") + "/jreap/web/right/auth/v1/navigation.form"
    FUEL_TOKEN = os.getenv("FUEL_TOKEN", "")
    async with httpx.AsyncClient() as client:
        try:
            client.cookies.set('jreapSid', FUEL_TOKEN)
            # 查询车牌号是否可以退煤
            response = await client.post(NAVIGATION_QUERY, headers=headers, timeout=30.0)
            response.raise_for_status()
            json_data = response.json()
            if json_data.get('flag') == 'error' and json_data.get('msg'):
                return f"请求失败: {json_data['msg']}"
            navData = json_data.get('result')
            allMenu = navData.get('allMenu')
            menulist = find_menu(allMenu, pageName)
            menu_info = []
            for item in menulist:
                page_name = item.get("name", "未知")
                page_id = item.get("id", "未知")
                # menu_info.append(f"跳转页面名称: {page_name}, 跳转页面名称Id: {page_id}")
                menu_info.append({"page_name": page_name, "page_id": page_id})
            return json.dumps(menu_info, ensure_ascii=False)
            # menu_info_str = "\n".join(menu_info)
            # return menu_info_str
        except httpx.HTTPStatusError as e:
            return f"HTTP 错误: {e.response.status_code}"

def find_menu(allMenu: list[dict[str, Any]], pageName: str) -> list[dict[str, Any]]:
    result = []
    for menu in allMenu:
        # menu.get('name')中包含pageName的话，就返回menu
        if menu.get('name').find(pageName) != -1:
            result.append(menu)
        if menu.get('children'):
            result.extend(find_menu(menu.get('children'), pageName))
    return result

          